<template>
  <div class="publishPost">
    <el-form
      ref="form"
      label-width="80px"
      :model="postForm"
      :rules="rules"
      hide-required-asterisk
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model.trim="postForm.title" type="text" placeholder="请输入帖子标题" />
      </el-form-item>
      <el-form-item label="所属板块" prop="plateId">
        <el-select v-model="postForm.plateId" placeholder="请选择所属板块">
          <el-option
            v-for="item in plateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor
          v-model="postForm.content"
          class="editor"
          api-key="no-api-key"
          :init="editInit"
        />
      </el-form-item>
      <el-button type="primary" style="width: 100%;" @click="handlePublishPost">发帖</el-button>
    </el-form>
  </div>
</template>

<script>
import { getPlateList } from '@/api/plate'
import { savePost } from '@/api/post'
import Editor from '@tinymce/tinymce-vue'
import { upload } from '@/api/upload'
import { formatDateTime } from '@/utils/dateUtil'
export default {
  name: 'PublishPost',
  components: {
    Editor
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      plateList: [],
      postForm: {
        plateId: undefined,
        title: undefined,
        content: '',
        publishDate: undefined
      },
      rules: {
        plateId: [{
          required: true,
          message: '请选择所属板块',
          trigger: 'blur'
        }],
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '请输入内容',
          trigger: 'blur'
        }]
      },
      editInit: {
        language: 'zh_CN',
        statusbar: false,
        plugins: 'image',
        images_upload_handler: (blobInfo, success, failure) => {
          // 创建一个 FormData 对象
          var formData = new FormData()
          // 将要上传的图片文件添加到 FormData 中
          formData.append('file', blobInfo.blob())
          upload(formData).then(res => {
            this.postForm.content += `<img src="${this.baseUrl + res.data.imageUrl}"/>`
            success('')
          }, err => {
            console.log(err)
            failure('')
          })
        }
      },
      isButtonLoading: false
    }
  },
  beforeMount() {
    this.getPlateList()
  },
  methods: {
    handlePublishPost() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isButtonLoading = true
          this.postForm.publishDate = formatDateTime(new Date())
          var regexp = new RegExp(`<img src="${this.baseUrl.replace('/', '')}`, 'gi')
          this.postForm.content = this.postForm.content.replace(regexp, `<img src="`)
          savePost(this.postForm).then(res => {
            this.isButtonLoading = false
            this.postForm = {
              plateId: undefined,
              title: undefined,
              content: '',
              publishDate: undefined
            }
            this.$router.push({
              path: '/postDetail',
              query: {
                postId: res.data.id
              }
            })
          }, err => {
            console.log(err)
            this.isButtonLoading = false
          })
        } else {
          console.log('表单验证有误')
        }
      })
    },
    async getPlateList() {
      const { data } = await getPlateList()
      this.plateList = data
    }
  }
}
</script>

<style lang="scss" scoped>
.publishPost {
  background-color: #fff;
  width: 80%;
  margin: 20px auto;
  padding: 20px 0;
  border-radius: 20px;
  box-shadow: 0 0 10px black;
  .el-form {
    margin: 20px;
    .editor {
      height: 380px;
    }
  }
}
</style>
